﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;

using System.Threading;

public partial class JobManage_CompanyBookingJobList : BasePage
{
    DataBase db = new DataBase();
    IJobHandler jobManage = new JobHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISystemHandler systemManage = new SystemHandler();
    ISyContainerModelHandler containerModelManage = new SyContainerModelHandler();
    private static bool isCancel = false;
    private static bool isPrint = false;
    private static bool isConfirm = false;
    private static bool isCancelJob = false;

    ISyContainerModelHandler modelManage = new SyContainerModelHandler();


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1089")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    if (strPermission.Contains("1065"))
                    {
                        isConfirm = true;
                    }
                    else
                    {
                        isConfirm = false;
                    }

                    if (strPermission.Contains("1063"))
                    {
                        isCancelJob = true;
                    }
                    else
                    {
                        isCancelJob = false;
                    }

                    if (strPermission.Contains("1073"))
                    {
                        isCancel = true;
                    }
                    else
                    {
                        isCancel = false;
                    }

                    if (strPermission.Contains("1070"))
                    {
                        isPrint = true;
                    }
                    else
                    {
                        isPrint = false;
                    }
                }
            }

            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "desc";
            FillDDl();

            dataBind();

            txtTotalVol.Text = "0";
            txtTotalWeight.Text = "0";
        }
    }

    #region FillDDl
    private void FillDDl()
    {
        //绑定托运人
        DataTable dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        lstShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstShipper.DataTextField = "HKShortName";
        }
        else
        {
            lstShipper.DataTextField = "CNShortName";
        }
        lstShipper.DataValueField = "PKID";
        lstShipper.DataBind();

        //工厂
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.GC.ToString("d")));
        //ddlVendor.DataSource = dt;
        //if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        //{
        //    ddlVendor.DataTextField = "ENGShortName";
        //}
        ddlVendor.Items.Add(new ListItem(Resources.Messages.PleaseSelect, "0"));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ListItem item = new ListItem();
            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                // ddlVendor.DataTextField = "HKShortName";
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["HKShortName"].ToString();
            }
            else
            {
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["CNShortName"].ToString();
                //ddlVendor.DataTextField = "CNShortName";
            }
            item.Value = dt.Rows[i]["PKID"].ToString();
            // ddlVendor.DataValueField = "PKID";
            ddlVendor.Items.Add(item);
        }
        // ddlVendor.DataBind();
        // ddlVendor.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //仓库
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.CK.ToString("d")));
        ddlWhouse.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlWhouse.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlWhouse.DataTextField = "HKShortName";
        }
        else
        {
            ddlWhouse.DataTextField = "CNShortName";
        }
        ddlWhouse.DataValueField = "PKID";
        ddlWhouse.DataBind();
        ddlWhouse.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //truck size
        string sqlStrm = "select * from Sy_ContainerModel where Status=@Status";
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@Status", 1);
        dt = modelManage.GetModelList(sqlStrm, parms);
        ddlTruckSize.DataSource = dt;
        ddlTruckSize.DataTextField = "Model";
        ddlTruckSize.DataValueField = "PKID";
        ddlTruckSize.DataBind();
        ddlTruckSize.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));
    }
    #endregion

    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        UsersQuery userQuery = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
        if (userQuery != null)
        {                        

            if (ViewState["Shipper"] != null)
            {
               // list.Add(new SqlParameter("@ShipperID", ViewState["ShipperID"].ToString()));
                sqlstr += " and ShipperID in (" + ViewState["Shipper"].ToString() + ")";
            }
            if (ViewState["Whse"] != null)
            {
                list.Add(new SqlParameter("@WhseID", ViewState["Whse"].ToString()));
                sqlstr += " and WhouseID=@WhseID";
            }

            if (ViewState["Vendor"] != null)
            {
                list.Add(new SqlParameter("@VendorID", ViewState["Vendor"].ToString()));
                sqlstr += " and VendorID=@VendorID";

            }

            if (ViewState["DateFrom"] != null && ViewState["DateTo"] != null)
            {
                list.Add(new SqlParameter("@DateFrom", ViewState["DateFrom"].ToString().ToString()));
                list.Add(new SqlParameter("@DateTo", ViewState["DateTo"].ToString()));
                sqlstr += " and JobDate between @DateFrom and @DateTo ";
            }
            else if (ViewState["DateFrom"] != null && ViewState["DateTo"] == null)
            {
                list.Add(new SqlParameter("@DateFrom", ViewState["DateFrom"].ToString().ToString()));
                sqlstr += " and JobDate >= @DateFrom ";
            }
            else if (ViewState["DateFrom"] == null && ViewState["DateTo"] != null)
            {
                list.Add(new SqlParameter("@DateTo", ViewState["DateTo"].ToString().ToString()));
                sqlstr += " and JobDate <= @DateTo ";
            }

            if (ViewState["SONO"] != null)
            {
                list.Add(new SqlParameter("@SONO", txtSONO.Text.Trim()));
                sqlstr += " and SONO like @SONO ";
            }
            list.Add(new SqlParameter("@Status", Enums.ShippingOrderStatus.CHECK.ToString("d")));
            list.Add(new SqlParameter("@Status2", Enums.ShippingOrderStatus.CONFIM.ToString("d")));
            list.Add(new SqlParameter("@Status3", Enums.ShippingOrderStatus.PRINT.ToString("d")));
            list.Add(new SqlParameter("@Status4", Enums.ShippingOrderStatus.CANCELCONFIM.ToString("d")));
            list.Add(new SqlParameter("@Status5", Enums.ShippingOrderStatus.MATECONFIRM.ToString("d")));
            sqlstr += " and (BN.Status = @Status or BN.Status=@Status2 or BN.Status=@Status3 or BN.Status=@Status4 or BN.Status=@Status5 )";

            if (systemManage.IsCompanyRoles2())//公司用户2
            {
                list.Add(new SqlParameter("@UserID", Session["UserID"].ToString()));

            }

            parms = list.ToArray();
        }
    }



    private void dataBind()
    {
        if (Session["UserID"] != null)
        {
            
            string sqlStr = string.Empty;

            if (systemManage.IsCompanyRoles2())//公司用户2
            {
                sqlStr = @"SELECT BN.*,BNDtl.*,
                        
                           (select CNShortName from Sy_Client as SC where SC.PKID=BN.Contractor) as ContractorCNShortName ,
                        (select ENGShortName from Sy_Client as SC where SC.PKID=BN.Contractor) as ContractorENGShortName,
                        (select HKShortName from Sy_Client as SC where SC.PKID=BN.Contractor) as ContractorHKShortName,
                             (SELECT [values] FROM(
            SELECT [values] = STUFF(REPLACE(REPLACE((
                SELECT DISTINCT LicenseNO FROM BN_SendTruck st INNER JOIN
                    BN_SendTruckDtl stDtl ON st.PKID = SendTruckID INNER JOIN
                    BN_Truck truck ON stDtl.TruckID = truck.PKID
                WHERE st.OrderID = BN.PKID AND
                    st.Contractor = BN.Contractor
                FOR XML AUTO
            ), '<truck LicenseNO=" + "\"" + "', ', '),'" + "\"" + @"/>', ''),1,1,'')
        )N) as LicenseNO,
        
              (select Model from Sy_ContainerModel where PKID=BNDtl.TruckSize) as Model 

                       FROM BN_ShippingOrder as BN 
join BN_ShippingOrderDtl as BNDtl  
on BN.PKID=BNDtl.OrderID
join bn_Booking as b 
on bn.BookingID=b.PKID 
join bn_bookingDtl as BDtl
on b.PKID=BDtl.BookingID 
join bn_BookingNoteDtl BookNDtl
on BDtl.BookingNoteDtlID =BookNDtl.PKID
join bn_BookingNote BookN 
on BookNDtl.BookingNoteID=Bookn.PKID
where Bookn.CreatedUser in(
select UserID from Users where  ClientID in(
select ClientID from Users where UserID=@UserID)) ";
            }
            else
            {
                sqlStr = @"SELECT BN.*,BNDtl.*,
                        
                           (select CNShortName from Sy_Client as SC where SC.PKID=BN.Contractor) as ContractorCNShortName ,
                        (select ENGShortName from Sy_Client as SC where SC.PKID=BN.Contractor) as ContractorENGShortName,
                        (select HKShortName from Sy_Client as SC where SC.PKID=BN.Contractor) as ContractorHKShortName,
                             (SELECT [values] FROM(
            SELECT [values] = STUFF(REPLACE(REPLACE((
                SELECT DISTINCT LicenseNO FROM BN_SendTruck st INNER JOIN
                    BN_SendTruckDtl stDtl ON st.PKID = SendTruckID INNER JOIN
                    BN_Truck truck ON stDtl.TruckID = truck.PKID
                WHERE st.OrderID = BN.PKID AND
                    st.Contractor = BN.Contractor
                FOR XML AUTO
            ), '<truck LicenseNO=" + "\"" + "', ', '),'" + "\"" + @"/>', ''),1,1,'')
        )N) as LicenseNO,
        
              (select Model from Sy_ContainerModel where PKID=BNDtl.TruckSize) as Model 

                       FROM BN_ShippingOrder as BN 
join BN_ShippingOrderDtl as BNDtl  
on BN.PKID=BNDtl.OrderID where 1=1 ";
            }

            SqlParameter[] parms = null;
            string clause = string.Empty;
            ProcessParms(ref clause, ref parms);
            sqlStr += clause;

            DataTable dt = jobManage.GetShippingOrder(sqlStr, parms);
            DataView view = dt.DefaultView;
            view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
            gvJobList.DataSource = view;
            gvJobList.DataBind();
            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotal.Text = dt.Rows.Count.ToString();
            }
            else
            {
                lblTotal.Text = "0";
            }
            divTruckSize.Visible = false;
            gvTruckList.DataSource = null;
            gvTruckList.DataBind();
            lblTotalTruck.Text = "0";
            txtTotalVol.Text = "0";
           txtTotalWeight.Text = "0";
        }
    }
    protected void gvJobList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvJobList.PageIndex = e.NewPageIndex;
        dataBind();

    }
    protected void gvJobList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       

        if (e.CommandName == "Confirm")//公司確認Job
        {
            BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(e.CommandArgument.ToString()));
            if (orderQuery != null)
            {
                if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CHECK.ToString("d"))
                {
                    SqlParameter[] parms = new SqlParameter[6];
                    parms[0] = new SqlParameter("@Status", Enums.ShippingOrderStatus.CONFIM.ToString("d"));//ShippingOrder 公司确认状态
                    parms[1] = new SqlParameter("@ConfirmUser", Session["UserID"].ToString());
                    parms[2] = new SqlParameter("@ConfirmDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd"));
                    parms[3] = new SqlParameter("@OrderID", e.CommandArgument.ToString());
                    //parms[4] = new SqlParameter("@BookingStatus",Enums.BookingStatus.CONFIRM.ToString("d"));
                    parms[4] = new SqlParameter("@BookingID", orderQuery.BookingID.ToString());
                    parms[5] = new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.CONFIRMBOOKING.ToString("d"));//BookingNoteDtl 公司确认job状态
                    string sqlStr = "update BN_ShippingOrder set Status=@Status,ConfirmUser=@ConfirmUser,ConfirmDate=@ConfirmDate where PKID=@OrderID;";
                    //sqlStr += "update BN_Booking set CBDate=@ConfirmDate,CBUser=@ConfirmUser where PKID=@BookingID;";
                    sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,CBDate=@ConfirmDate,CBUser=@ConfirmUser where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID));";
                    if (jobManage.ShippingOrderUpdate(sqlStr, parms))
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.CompanyConfirmJobSuccess, "CompanyBookingJobList.aspx", UpdatePanel1);
                    }
                    else
                    {
                        Jscript.AlertInAjax(Resources.Messages.CompanyConfirmJobFailed, UpdatePanel1);
                    }
                }
                else
                {
                    Jscript.AlertInAjax(Resources.Messages.JobConfirm, UpdatePanel1);
                    return;
                }
            }
        }
        if (e.CommandName == "CancelConfirm")//取消確認Job
        {
            BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(e.CommandArgument.ToString()));
            if (orderQuery != null)
            {
                if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CONFIM.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.PRINT.ToString("d"))
                {
                    SqlParameter[] parms = new SqlParameter[5];
                    parms[0] = new SqlParameter("@Status", Enums.ShippingOrderStatus.CANCELCONFIM.ToString("d"));
                    parms[1] = new SqlParameter("@CancelConfirmUser", Session["UserID"].ToString());
                    parms[2] = new SqlParameter("@CancelConfirmDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd"));
                    parms[3] = new SqlParameter("@OrderID", e.CommandArgument.ToString());
                    parms[4] = new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.COCANCEL.ToString("d"));//BookingNoteDtl 公司取消确认job状态
                    string sqlStr = "update BN_ShippingOrder set Status=@Status,CancelConfirmUser=@CancelConfirmUser,CancelConfirmDate=@CancelConfirmDate where PKID=@OrderID;";
                    sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,CancelConfirmDate=@CancelConfirmDate,CancelConfirmUser=@CancelConfirmUser where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID));";

                    if (jobManage.ShippingOrderUpdate(sqlStr, parms))
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.CanceledConfirmJobSuccess, "CompanyBookingJobList.aspx", UpdatePanel1);
                    }
                    else
                    {
                        Jscript.AlertInAjax(Resources.Messages.CanceledConfirmJobFailed, UpdatePanel1);
                    }
                }
                else
                {
                    Jscript.AlertInAjax(Resources.Messages.JobCancelConfirm, UpdatePanel1);
                    return;
                }
            }
        }

        if (e.CommandName == "Cal")//取消Job
        {
            BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(e.CommandArgument.ToString()));

            if (orderQuery != null)
            {
                // if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CHECK.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CANCELCONFIM.ToString("d"))
                //if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CEXPEDITEDTRUCK.ToString("d") || orderQuery.Status.ToString() ==Enums.ShippingOrderStatus.NEW.ToString("d"))//当状态为取消派车状态时才能取消Job
                //{
                SqlParameter[] parms = new SqlParameter[6];
                parms[0] = new SqlParameter("@Status", Enums.ShippingOrderStatus.CANCEL.ToString("d"));
                parms[1] = new SqlParameter("@CancelUser", Session["UserID"].ToString());
                parms[2] = new SqlParameter("@CancelDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd"));
                parms[3] = new SqlParameter("@OrderID", e.CommandArgument.ToString());
                parms[4] = new SqlParameter("@BNDtlStatus", Enums.BookingNoteDtlStatus.CCANCEL.ToString("d"));
                // parms[5] = new SqlParameter("@BookingStatus", Enums.BookingStatus.NEW.ToString("d"));
                 parms[5] = new SqlParameter("@Contractor", System.DBNull.Value);
                string sqlStr = @"update BN_ShippingOrder set Status=@Status,CancelUser=@CancelUser,CancelDate=@CancelDate where PKID=@OrderID;
                                     update BN_BookingDtl set Contractor=@Contractor where BookingID in(select BookingID from BN_ShippingOrder where PKID=@OrderID);
                                    UPDATE BN_BookingNoteDtl SET Status=@BNDtlStatus, CJCancelDate=@CancelDate, CJCancelUser=@CancelUser
                                    WHERE PKID IN (SELECT DISTINCT BookingNoteDtlID FROM BN_BookingDtl WHERE PKID IN 
                                        (SELECT DISTINCT BookingDtlID FROM BN_ShippingOrderDtl WHERE OrderID=@OrderID));";

                // update BN_Booking set  Status=@BookingStatus where PKID in(select BookingID from BN_ShippingOrder where PKID=@OrderID);
                // update BN_BookingDtl set Contractor=@Contractor where BookingID in(select BookingID from BN_ShippingOrder where PKID=@OrderID);
                //取消派车时删除已派车辆
                sqlStr += @"delete from BN_SendTruckDtl where SendTruckID in(select PKID from BN_SendTruck where OrderID=@OrderID);";
                sqlStr += @" delete from BN_SendTruck where OrderID=@OrderID;";

                if (jobManage.ShippingOrderUpdate(sqlStr, parms))
                {
                    Jscript.AlertAndRedirectInAjax(Resources.Messages.CancelSuccess, "CompanyBookingJobList.aspx", UpdatePanel1);
                }
                else
                {
                    Jscript.AlertInAjax(Resources.Messages.CancelFailed, UpdatePanel1);
                }
                //}
                //else
                //{
                //    Jscript.AlertInAjax(Resources.Messages.JobCancel, UpdatePanel1);
                //    return;
                //}
            }
        }

        dataBind();
    }
    protected void gvJobList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            string item = string.Empty;
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                item += lstSelShipper.Items[i].Value + ",";
            }
            ViewState["Shipper"] = item.Substring(0, item.Length - 1);
        }
        else
        {
            ViewState["Shipper"] = null;
        }

        if (ddlVendor.SelectedValue != "0")
        {

            ViewState["Vendor"] = ddlVendor.SelectedValue;
        }
        else
        {
            ViewState["Vendor"] = null;
        }
        if (ddlWhouse.SelectedValue != "0")
        {

            ViewState["Whse"] = ddlWhouse.SelectedValue;
        }
        else
        {
            ViewState["Whse"] = null;
        }

        if (txtDateFrom.Text != string.Empty && txtDateTo.Text != string.Empty)
        {
            ViewState["DateFrom"] = txtDateFrom.Text.Trim() + " 00:00:00";

            ViewState["DateTo"] = txtDateTo.Text.Trim() + " 23:59:59";
        }
        else if (txtDateFrom.Text != string.Empty && txtDateTo.Text == string.Empty)
        {
            ViewState["DateFrom"] = txtDateFrom.Text.Trim() + " 23:59:59";

            ViewState["DateTo"] = null;
        }
        else if (txtDateFrom.Text == string.Empty && txtDateTo.Text != string.Empty)
        {

            ViewState["DateFrom"] = null;
            ViewState["DateTo"] = txtDateTo.Text.Trim() + " 23:59:59";
        }
        else
        {
            ViewState["DateFrom"] = null;
            ViewState["DateTo"] = null;
        }

        if (txtSONO.Text != string.Empty)
        {
            ViewState["SONO"] = txtSONO.Text.Trim();
        }
        else
        {
            ViewState["SONO"] = null;
        }

        dataBind();
    }


    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvJobList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvJobList.PageCount)
            {
                this.gvJobList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
                Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);
                return;
            }
        }
        catch
        {
            // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
            Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);

        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvJobList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }

    public string GetClient(object id)
    {
        return systemManage.GetClient(id);
    }

    public string GetUserName(object userID)
    {
        return systemManage.GetUserName(userID);
    }

    protected void gvJobList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //这里的处理是为了回显之前选中的情况   
        if (e.Row.RowIndex > -1 && this.SelectedItems != null)
        {
            DataRowView row = e.Row.DataItem as DataRowView;
            CheckBox cb = e.Row.FindControl("CheckBox1") as CheckBox;
            if (this.SelectedItems.Contains(row["PKID"].ToString()))
                cb.Checked = true;
            else
                cb.Checked = false;
        }   

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

           // RadioButton rb = (RadioButton)e.Row.FindControl("radSelect");
           //rb.Attributes.Add("onclick", "judge(this)");//给RadioButton添加onclick属性

            LinkButton btnConfirm = (LinkButton)e.Row.FindControl("lbtnConfirm");
            HiddenField hidOrderID = (HiddenField)e.Row.FindControl("hidOrderID");
            Label lblPrint = (Label)e.Row.FindControl("lblPrint");
            LinkButton btnCancelConfirm = (LinkButton)e.Row.FindControl("lbtnCancelConfirm");
            LinkButton lbtnCal = (LinkButton)e.Row.FindControl("lbtnCal");

            if (hidOrderID.Value != string.Empty)
            {
                BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(hidOrderID.Value));
                if (orderQuery != null)
                {
                    if (isConfirm)
                    {

                        if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CHECK.ToString("d"))
                        {
                            btnConfirm.Visible = true;
                        }
                        else
                        {
                            btnConfirm.Visible = false;
                        }
                    }
                    else
                    {
                        btnConfirm.Visible = false;
                    }

                    if (isCancelJob)
                    {
                        lbtnCal.Visible = true;
                    }
                    else
                    {
                        lbtnCal.Visible = false;
                    }

                    if (isPrint)
                    {
                        if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CONFIM.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.PRINT.ToString("d"))
                        {
                            lblPrint.Visible = true;
                        }
                        else
                        {
                            lblPrint.Visible = false;
                        }
                    }
                    else
                    {
                        lblPrint.Visible = false;
                    }

                    if (isCancel)
                    {
                        if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CONFIM.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.PRINT.ToString("d"))
                        {
                            btnCancelConfirm.Visible = true;
                        }
                        else
                        {
                            btnCancelConfirm.Visible = false;
                        }
                    }
                    else
                    {
                        btnCancelConfirm.Visible = false;
                    }                    
                }
            }
        }
    }
       
    //protected void radSelect_CheckedChanged(object sender, EventArgs e)
    //{
    //    decimal vol = 0;
    //    double weight = 0d;
    //    foreach (GridViewRow row in gvJobList.Rows)
    //    {
    //        RadioButton rad = (RadioButton)row.FindControl("radSelect");
    //        HiddenField hidPKID = (HiddenField)row.FindControl("hidValue");
    //        if (rad.Checked)
    //        {
    //            divTruckSize.Visible = true;
    //            ViewState["OrderByT"] = "TruckID";
    //            ViewState["AccendingT"] = "desc";
    //            ViewState["OrderID"] = hidPKID.Value;
    //            dataBindTruck(int.Parse(ViewState["OrderID"].ToString()));

               
    //            string id = hidPKID.Value;

    //            string sqlStr = "select * from BN_ShippingOrderDtl where OrderID=@OrderID";
    //            SqlParameter[] parms = new SqlParameter[1];
    //            parms[0] = new SqlParameter("@OrderID", id);
    //            DataTable dt = jobManage.GetShippingOrderDtl(sqlStr, parms);
    //            if (dt != null && dt.Rows.Count > 0)
    //            {
    //                vol += decimal.Parse(dt.Rows[0]["Vol"].ToString());
    //                weight += double.Parse(dt.Rows[0]["GrossWT"].ToString());
    //            }          

    //        }
    //    }

    //    txtTotalVol.Text = vol.ToString();
    //    txtTotalWeight.Text = weight.ToString();
    //}


    //truck
    private void dataBindTruck(string OrderIDs)
    {

        string sqlStr = @"select*, TruckID,
(select LicenseNO from BN_Truck where PKID=ST.TruckID) as LicenseNO,
(select Model from Sy_ContainerModel where PKID=ST.TypeID) as TruckSizeName,
  Driver,TypeID 
from BN_SendTruckDtl as ST
 where SendTruckID in(select PKID from BN_SendTruck where OrderID!=@OrderID and OrderID in (" + ViewState["OrderIDs"].ToString() + ")) ";
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@OrderID", "0");

        DataTable dt = jobManage.GetShippingOrderDtl(sqlStr, parms);//获取job的已派车信息
        gvTruckList.DataSource = dt;
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderByT"] + " " + ViewState["AccendingT"];
        gvTruckList.DataSource = view;
        gvTruckList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotalTruck.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotalTruck.Text = "0";
        }
    }


    protected void ddlPagesTruck_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvTruckList.PageSize = int.Parse(ddlPagesTruck.SelectedValue);
        dataBindTruck(ViewState["OrderIDs"].ToString());
    }


    protected void gvTruckList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvTruckList.PageIndex = e.NewPageIndex;
        dataBindTruck(ViewState["OrderIDs"].ToString());
    }


    protected void gvTruckList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderByT"].ToString().ToLower())
        {
            if (ViewState["AccendingT"].ToString().ToLower() == "asc")
            {
                ViewState["AccendingT"] = "desc";
            }
            else
            {
                ViewState["AccendingT"] = "asc";
            }
        }
        else
        {
            ViewState["OrderByT"] = e.SortExpression;
        }
        dataBindTruck(ViewState["OrderIDs"].ToString());
    }

    protected void gvTruckList_RowDataBound(object sender, GridViewRowEventArgs e)
    {       
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlType = (DropDownList)e.Row.FindControl("ddlType");
            HiddenField hidType = (HiddenField)e.Row.FindControl("hidType");
            ddlType.DataSource = GetModel();
            ddlType.DataTextField = "Model";
            ddlType.DataValueField = "PKID";
            ddlType.DataBind();
            // ddlType.Items.Insert(0, new ListItem("请选择...", "0"));

            ddlType.SelectedValue = hidType.Value;
        }

        //这里的处理是为了回显之前选中的情况   
        if (e.Row.RowIndex > -1 && this.SelectedItems2 != null)
        {
            DataRowView row = e.Row.DataItem as DataRowView;
            CheckBox cb = e.Row.FindControl("CheckBox2") as CheckBox;
            if (this.SelectedItems2.Contains(row["PKID"].ToString()))
                cb.Checked = true;
            else
                cb.Checked = false;
        }
    }

    protected void lbtnGoTruck_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvTruckList.BottomPagerRow.FindControl("txtPagesTruck"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvTruckList.PageCount)
            {
                this.gvTruckList.PageIndex = i;
                //数据绑定
                dataBindTruck(ViewState["OrderIDs"].ToString());
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);

        }
    }

    public string GetDriver(object id)
    {
        return systemManage.GetDriver(id);
    }

    private int GetClientID()
    {
        int clientID = 0;
        if (Session["UserID"] != null)
        {
            UsersQuery query = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
            if (query != null)
            {
                clientID = query.ClientID;
            }
        }
        return clientID;
    }       

    public string GetType(object typeID)
    {
        string model = string.Empty;
        Sy_ContainerModelQuery query = containerModelManage.GetModel(int.Parse(typeID.ToString()));
        if (query != null)
        {
            return model = query.Model;
        }
        return model;
    }

    private DataTable GetModel()
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@Status", "1");
        string sqlSTr = "select * from Sy_ContainerModel where Status=@Status";

        return containerModelManage.GetModelList(sqlSTr, parms);

    }

    #region //全选代码

    protected ArrayList SelectedItems
    {
        get
        {
            return (ViewState["mySelectedItems"] != null) ? (ArrayList)ViewState["mySelectedItems"] : null;
        }
        set
        {
            ViewState["mySelectedItems"] = value;
        }
    }

    protected ArrayList SelectedItems2
    {
        get
        {
            return (ViewState["mySelectedItems2"] != null) ? (ArrayList)ViewState["mySelectedItems2"] : null;
        }
        set
        {
            ViewState["mySelectedItems2"] = value;
        }
    }


    protected void CollectSelected()
    {
        ArrayList selectedItems = null;
        if (this.SelectedItems == null)
            selectedItems = new ArrayList();
        else
            selectedItems = this.SelectedItems;

        for (int i = 0; i < this.gvJobList.Rows.Count; i++)
        {
            HiddenField hidID = (HiddenField)gvJobList.Rows[i].Cells[1].FindControl("hidID");
            string id = hidID.Value;
            CheckBox cb = this.gvJobList.Rows[i].FindControl("CheckBox1") as CheckBox;
            if (selectedItems.Contains(id) && !cb.Checked)
                selectedItems.Remove(id);
            if (!selectedItems.Contains(id) && cb.Checked)
                selectedItems.Add(id);
        }
        this.SelectedItems = selectedItems;
    }

    protected void CollectSelected2()
    {
        ArrayList selectedItems = null;
        if (this.SelectedItems2 == null)
            selectedItems = new ArrayList();
        else
            selectedItems = this.SelectedItems2;

        for (int i = 0; i < this.gvTruckList.Rows.Count; i++)
        {
            HiddenField hidID = (HiddenField)gvTruckList.Rows[i].Cells[1].FindControl("hidID");
            string id = hidID.Value;
            CheckBox cb = this.gvTruckList.Rows[i].FindControl("CheckBox2") as CheckBox;
            if (selectedItems.Contains(id) && !cb.Checked)
                selectedItems.Remove(id);
            if (!selectedItems.Contains(id) && cb.Checked)
                selectedItems.Add(id);
        }
        this.SelectedItems2 = selectedItems;
    }

    protected void gvJobList_DataBinding(object sender, EventArgs e)
    {  //在每一次重新绑定之前，需要调用CollectSelected方法从当前页收集选中项的情况   
        CollectSelected();

    }

    protected void gvTruckList_DataBinding(object sender, EventArgs e)
    {  //在每一次重新绑定之前，需要调用CollectSelected方法从当前页收集选中项的情况   
        CollectSelected2();

    }
    #endregion


    protected void btnSave_Click(object sender, EventArgs e)
    {

        CollectSelected();
        if (this.SelectedItems != null && this.SelectedItems.Count > 0)
        {
            SqlParameter[] parms = null;
            List<SqlParameter> list = new List<SqlParameter>();
            string sqlStr = string.Empty;

            if (ddlTruckSize.SelectedValue != "0" || txtAppointmentNO.Text != string.Empty)
            {
                if (ddlTruckSize.SelectedValue != "0")
                {
                    list.Add(new SqlParameter("@TruckSize", ddlTruckSize.SelectedValue));
                }
                if (txtAppointmentNO.Text != string.Empty)
                {
                    list.Add(new SqlParameter("@Appointment", txtAppointmentNO.Text.Trim()));
                }

                for (int i = 0; i < SelectedItems.Count; i++)
                {

                    BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(SelectedItems[i].ToString()));
                    if (orderQuery != null)
                    {
                        //Status 为打印暂收证明和尾纸已确认不能修改
                        // if (!orderQuery.Status.ToString().Equals(Enums.ShippingOrderStatus.PRINT.ToString("d")) && !orderQuery.Status.ToString().Equals(Enums.ShippingOrderStatus.MATECONFIRM.ToString("d")))
                        //{
                        list.Add(new SqlParameter("@OrderID" + i.ToString(), SelectedItems[i].ToString()));

                        if (ddlTruckSize.SelectedValue != "0")
                        {
                            sqlStr += "UPDATE BN_ShippingOrderDtl set TruckSize=@TruckSize where OrderID=@OrderID" + i.ToString() + ";";

                        }
                        if (txtAppointmentNO.Text != string.Empty)
                        {
                            sqlStr += "UPDATE BN_ShippingOrder set Appointament=@Appointment where PKID=@OrderID" + i.ToString() + ";";
                        }
                        // }
                    }
                }

                CollectSelected2();
                if (this.SelectedItems2 != null && this.SelectedItems2.Count > 0)
                {
                    if (ddlTruckSize.SelectedValue != "0")
                    {
                        for (int j = 0; j < SelectedItems2.Count; j++)
                        {
                            list.Add(new SqlParameter("@SendTruckDtlID" + j.ToString(), SelectedItems2[j].ToString()));
                            sqlStr += "UPDATE BN_SendTruckDtl set TypeID=@TruckSize where PKID=@SendTruckDtlID" + j.ToString() + ";";
                        }
                    }
                }

                parms = list.ToArray();
                if (jobManage.ShippingOrderUpdate(sqlStr, parms))
                {
                    if (ddlTruckSize.SelectedValue != "0" && txtAppointmentNO.Text == string.Empty)
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.UpdateTruckSizeSuccess, "CompanyBookingJobList.aspx", UpdatePanel1);
                    }
                    else if (ddlTruckSize.SelectedValue != "0" && txtAppointmentNO.Text != string.Empty)
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.UpdateTruckAppointmentSuccess, "CompanyBookingJobList.aspx", UpdatePanel1);

                    }
                    else
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.UpdateAppointmentSuccess, "CompanyBookingJobList.aspx", UpdatePanel1);

                    }
                }
                else
                {
                    if (ddlTruckSize.SelectedValue != "0" && txtAppointmentNO.Text == string.Empty)
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.UpdateTruckSizeFailed, "CompanyBookingJobList.aspx", UpdatePanel1);
                    }
                    else if (ddlTruckSize.SelectedValue != "0" && txtAppointmentNO.Text != string.Empty)
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.UpdateTruckAppointmentfailed, "CompanyBookingJobList.aspx", UpdatePanel1);

                    }
                    else
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.UpdateAppointmentfailed, "CompanyBookingJobList.aspx", UpdatePanel1);

                    }

                }
            }

        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (lstShipper.SelectedValue != string.Empty)
        {
            for (int i = 0; i < lstShipper.Items.Count; i++)
            {
                bool issel = false;
                if (lstShipper.Items[i].Selected)
                {
                    for (int j = 0; j < lstSelShipper.Items.Count; j++)
                    {
                        if (lstShipper.Items[i].Value == lstSelShipper.Items[j].Value)
                        {
                            issel = true;
                            break;
                        }
                    }

                    if (!issel)
                    {
                        ListItem item = new ListItem();
                        item.Text = lstShipper.Items[i].Text;
                        item.Value = lstShipper.Items[i].Value;
                        lstSelShipper.Items.Add(item);
                    }
                }
            }
        }
        else
        {

        }

    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            ListItemCollection lstColl = new ListItemCollection();
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                if (!lstSelShipper.Items[i].Selected)
                {
                    ListItem item = new ListItem(lstSelShipper.Items[i].Text, lstSelShipper.Items[i].Value);
                    lstColl.Add(item);
                }
            }
            if (lstColl != null && lstColl.Count > 0)
            {
                lstSelShipper.Items.Clear();
                for (int j = 0; j < lstColl.Count; j++)
                {
                    lstSelShipper.Items.Add(lstColl[j]);
                }
            }
            else
            {
                lstSelShipper.Items.Clear();
            }

        }
    }

    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        decimal vol = 0;
        double weight = 0d;
        string selID = string.Empty;
        for (int i = 0; i < this.gvJobList.Rows.Count; i++)
        {
            HiddenField hidID = (HiddenField)gvJobList.Rows[i].Cells[1].FindControl("hidID");
            string id = hidID.Value;
            CheckBox cb = this.gvJobList.Rows[i].FindControl("CheckBox1") as CheckBox;
            if (cb.Checked)
            {
                selID += id + ",";
                string sqlStr = "select * from BN_ShippingOrderDtl where OrderID=@OrderID";
                SqlParameter[] parms = new SqlParameter[1];
                parms[0] = new SqlParameter("@OrderID", id);
                DataTable dt = jobManage.GetShippingOrderDtl(sqlStr, parms);
                if (dt != null && dt.Rows.Count > 0)
                {
                    vol += decimal.Parse(dt.Rows[0]["Vol"].ToString());
                    weight += double.Parse(dt.Rows[0]["GrossWT"].ToString());
                }
            }
        }
        txtTotalVol.Text = vol.ToString();
        txtTotalWeight.Text = weight.ToString();
        if (selID != null && selID != string.Empty)
        {
            ViewState["OrderByT"] = "TruckID";
            ViewState["AccendingT"] = "desc";
            selID = selID.Substring(0, selID.Length - 1);
            ViewState["OrderIDs"] = selID;
            divTruckSize.Visible = true;
            dataBindTruck(selID);
        }
        else
        {
            divTruckSize.Visible = false;
            gvTruckList.DataSource = null;
            gvTruckList.DataBind();
            lblTotalTruck.Text = "0";
        }
    }

    protected void chkAll_CheckedChanged(object sender, EventArgs e)
    {
        decimal vol = 0;
        double weight = 0d;
        string selID = string.Empty;
        for (int i = 0; i < this.gvJobList.Rows.Count; i++)
        {
            HiddenField hidID = (HiddenField)gvJobList.Rows[i].Cells[1].FindControl("hidID");
            string id = hidID.Value;
            CheckBox cb = this.gvJobList.Rows[i].FindControl("CheckBox1") as CheckBox;
            if (cb.Checked)
            {
                selID += id + ",";
                string sqlStr = "select * from BN_ShippingOrderDtl where OrderID=@OrderID";
                SqlParameter[] parms = new SqlParameter[1];
                parms[0] = new SqlParameter("@OrderID", id);
                DataTable dt = jobManage.GetShippingOrderDtl(sqlStr, parms);
                if (dt != null && dt.Rows.Count > 0)
                {
                    vol += decimal.Parse(dt.Rows[0]["Vol"].ToString());
                    weight += double.Parse(dt.Rows[0]["GrossWT"].ToString());
                }
            }

        }
        txtTotalVol.Text = vol.ToString();
        txtTotalWeight.Text = weight.ToString();
        if (selID != null && selID != string.Empty)
        {
            divTruckSize.Visible = true;
            ViewState["OrderByT"] = "PKID";
            ViewState["AccendingT"] = "desc";
            selID = selID.Substring(0, selID.Length - 1);
            ViewState["OrderIDs"] = selID;

            dataBindTruck(selID);
        }
        else
        {
            divTruckSize.Visible = false;
            gvTruckList.DataSource = null;
            gvTruckList.DataBind();
            lblTotalTruck.Text = "0";
        }
    }

    protected void btnMupConfirm_Click(object sender, EventArgs e)
    {
        CollectSelected();
        if (this.SelectedItems != null && this.SelectedItems.Count > 0)
        {
            string sqlStr = string.Empty;
            List<SqlParameter> list = new List<SqlParameter>();
            SqlParameter[] parms = null;
            list.Add(new SqlParameter("@Status", Enums.ShippingOrderStatus.CONFIM.ToString("d")));//ShippingOrder 公司确认状态
            list.Add(new SqlParameter("@ConfirmUser", Session["UserID"].ToString()));
            list.Add(new SqlParameter("@ConfirmDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd")));
            list.Add(new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.CONFIRMBOOKING.ToString("d")));//BookingNoteDtl 公司确认job状态

            for (int i = 0; i < this.SelectedItems.Count; i++)
            {
                BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(SelectedItems[i].ToString()));
                if (orderQuery != null)
                {
                    if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CHECK.ToString("d"))
                    {
                        list.Add(new SqlParameter("@OrderID" + i.ToString(), SelectedItems[i].ToString()));
                        list.Add(new SqlParameter("@BookingID" + i.ToString(), orderQuery.BookingID.ToString()));

                        sqlStr += "update BN_ShippingOrder set Status=@Status,ConfirmUser=@ConfirmUser,ConfirmDate=@ConfirmDate where PKID=@OrderID" + i.ToString() + ";";
                        //sqlStr += "update BN_Booking set CBDate=@ConfirmDate,CBUser=@ConfirmUser where PKID=@BookingID;";
                        sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,CBDate=@ConfirmDate,CBUser=@ConfirmUser where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID" + i.ToString() + "));";

                    }
                }
            }

            parms = list.ToArray();
            if (jobManage.ShippingOrderUpdate(sqlStr, parms))
            {
                Jscript.AlertAndRedirectInAjax(Resources.Messages.CompanyConfirmJobSuccess, "CompanyManageJobList.aspx", UpdatePanel1);
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.CompanyConfirmJobFailed, UpdatePanel1);
            }
        }

    }
}
